<template>
  <commonformdialog
    :isshowDialogs="isshowDialog"
    :dialogTitle="dialogTitle"
    @closetextDialog="closeDialog"
    @confirmbtn="confirmbtn"
    :dialogWidth="'45%'"
    :topHeight='"8vh"'
  >
    <div class="formarea" >
      <el-form
        ref="studentform"
        :model="studentforms"
        :rules="rules"
        size="small"
        label-width="92px"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="学员姓名" prop="name">
              <el-input
                v-model="studentforms.name"
                placeholder="请输入学员姓名"
                clearable
                :disabled="true"
                :style="{ width: '100%' }"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号" prop="tel">
              <el-input
                v-model="studentforms.tel"
                placeholder="请输入手机号"
                clearable
                :disabled="true"
                :style="{ width: '100%' }"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="申领类型" prop="apply_type">
              <el-select
                v-model="studentforms.apply_type"
                placeholder="请选择申领类型"
                clearable
                @change="changeApplyType"
                :style="{ width: '100%' }"
              >
                <el-option
                  v-for="(item, index) in apply_typeOptions"
                  :key="index"
                  :label="item.title"
                  :value="item.id"
                  :disabled="item.disabled"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="学习班型" prop="package_id">
              <el-select
              :disabled="studentforms.apply_type==''"
                v-model="studentforms.package_id"
                placeholder="请选择学习班型"
                clearable
                :style="{ width: '100%' }"
                @change="changepackage_id"
              >
                <el-option
                  v-for="(item, index) in learntypeOptions"
                  :key="index"
                  :label="item.title"
                  :value="item.id"
                  :disabled="item.disabled"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="班型费用" prop="course_fee">
              <el-input
                :disabled="true"
                v-model="studentforms.course_fee"
                placeholder="请输入班型费用"
                clearable
                :style="{ width: '100%' }"
              >
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="交费类型" prop="pay_type">
              <el-select
                :disabled="true"
                v-model="studentforms.pay_type"
                placeholder="请选择交费类型"
                clearable
                :style="{ width: '100%' }"
              >
                <el-option
                  v-for="(item, index) in paytypeOptions"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                  :disabled="item.disabled"
                ></el-option>
              </el-select>
            </el-form-item>

          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="优惠金额" prop="discounts">
              <el-input
               :disabled='isdiscounts'
                v-model="studentforms.discounts"
                placeholder="请输入优惠金额"
                clearable
                @input="discountsinput"
                :style="{ width: '100%' }"
              >
                <template slot="append">元</template>
              </el-input>
            </el-form-item>

          </el-col>
          <el-col :span="12">

          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">

          </el-col>
          <el-col :span="12">
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="费用信息" prop="">
            <ul class="moneylist" v-if="isshowDialog">
              <li>
                <span>标准：{{studentforms.course_fee||0}}元</span>
              </li>
              <li>
                <span>优惠：{{studentforms.discounts||0}}元</span>
              </li>
              <li>
                <span>应收：{{receivableprice||0}}元</span>
              </li>
              <li>
                <span style="color:rgb(71, 98, 254);">实收：{{officialprice||0}}元</span>
              </li>
              <li>
                <span style="color:red;">欠费：{{arrearage||0}}元</span>
              </li>
            </ul>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="支付方式" prop="pay_typeprice" v-if="isshowDialog">
              <div class="paytypearea">

                <el-input
                 v-for="(item,index) in pay_typeOption"
                 :key="index"
                 :disabled='ispayType'
                  v-model="paytypeprice[item.alias]"
                  class="payTypeinput"
                  placeholder="金额"
                  :style="{ width: '20%' }"
                  @input="paypriceinput"
                >
                  <template slot="prepend">{{item.title}}</template>
                </el-input>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="交费日期" prop="cost_time">
              <el-date-picker
                v-model="studentforms.cost_time"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                :style="{ width: '100%' }"
                placeholder="请选择交费日期"
                clearable
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12"></el-col>
          <el-col :span="12">
            <el-form-item label="报名材料" prop="enroll_data">
              <el-checkbox-group
                v-model="studentforms.enroll_data"
                size="medium"
              >
                <el-checkbox
                  v-for="(item, index) in bmclOptions"
                  :key="index"
                  :label="item.value"
                  :disabled="item.disabled"
                >
                  {{ item.label }}
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <!-- 报名备注  录入备注 两种 报名备注信息 -->
            <el-form-item label="报名备注" prop="enroll_remark">
              <el-input
                v-model="studentforms.enroll_remark"
                type="textarea"
                placeholder="请输入备注"
                :autosize="{ minRows: 4, maxRows: 4 }"
                :style="{ width: '100%' }"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
  </commonformdialog>
</template>

<script>
import commonformdialog from '@/components/commondialog/commondialog'
//引入图片上传组件
import uploadimg from '@/components/uploadimg/uploadimg'
import { isincloudOption } from '@/utils/index'
//api
import {
  createData,
  getxlcOption,
  getRead,
  getcourseOption,
  updateData,
  applyStudet
} from '@/api/student'
import { getSessionStorage } from '@/utils/accessToken'
//api
import { readData } from '@/api/course'
//utils
import {isObjectvalue} from '@/utils'
export default {
  data() {
     var validatepay = (rule, value, callback) => {
       if(!isObjectvalue(this.paytypeprice)){
         callback(new Error('请输入支付方式'));
       }else{
         callback()
       }
      };
    return {
      //优惠金额输入框是否禁用
      isdiscounts:true,
      //是否禁用支付方式
      ispayType:false,
      //用户id
      id:'',
      //支付方式
      paytypeprice: {
        wechat: '',
        alipay:'',
        money:'',
        pos:'',
        other:'',
        transfer:''
      },
      studentforms: {
       name:'',
      tel:'',
      apply_type:'',
      package_id:'',
      course_fee:'',
      pay_type:'',
      discounts:'',
      cost_time:'',
      enroll_data:[],
      enroll_remark:''
      },
      rules: {
        apply_type: [
          {
            required: true,
            message: '请选择申领类型',
            trigger: 'change',
          },
        ],
        name: [
          {
            required: true,
            message: '请输入姓名',
            trigger: 'blur',
          },
        ],
        tel: [
          {
            required: true,
            message: '请输入手机号',
            trigger: 'blur',
          },
          {
            pattern: /^1(3|4|5|7|8|9|6)\d{9}$/,
            message: '手机号格式错误',
            trigger: 'blur',
          },
        ],
        cost_time:[
          {
              required: true,
            message: '请选择交费日期',
            trigger: 'change',
          }
        ],
        package_id: [
          {
            required: true,
            message: '请选择学习班型',
            trigger: 'change',
          },
        ],
        course_fee: [
          {
            required: true,
            message: '请输入班型费用',
            trigger: 'blur',
          },
        ],
        pay_type: [
          {
            required: true,
            message: '请选择交费类型',
            trigger: 'change',
          },
        ],
        discounts: [
          {
            required: false,
            message: '请输入优惠金额',
            trigger: 'blur',
          },
        ],
        pay_fee: [
          {
            required: false,
            message: '请输入已交金额',
            trigger: 'blur',
          },
        ],
        pay_time: [
          {
            required: false,
            message: '请选择交费日期',
            trigger: 'change',
          },
        ],
        enroll_data: [
          {
            required: false,
            type: 'array',
            message: '请选择报名材料',
            trigger: 'change',
          },
        ],
        enroll_remark: [],
        pay_typeprice:[
           {
             required: true,
             validator: validatepay,
             trigger: 'change'
          }
        ]
      },
      pay_typeOption:[],
      apply_typeOptions: [],
      learntypeOptions: [],
      paytypeOptions: [
        {
          label: '全款',
          value: 1,
        },
        {
          label: '分期',
          value: 2,
        },
      ],
      bmclOptions: [
        {
          label: '身份证',
          value: 1,
        },
        {
          label: '体检表',
          value: 2,
        },
        {
          label: '驾驶证回执照片',
          value: 3,
        },
      ],
    }
  },
  components: {
    commonformdialog,
    uploadimg,
  },
  props: {
    //是否显示弹窗
    isshowDialog: {
      type: Boolean,
      default: false,
      required: true,
    },
    //表单的名字
    dialogTitle: {
      type: String,
      default: '',
      required: true,
    },
    //是编辑还是新增
    formType: {
      type: Number,
      default: 0,
    },
  },
  methods: {
    //输入支付金额
    paypriceinput(){

      if(!this.studentforms.course_fee){
        this.$message.error('请先选择班型！');
        for(var k in this.paytypeprice){
          this.paytypeprice[k] = ''
        }
        // this.studentforms.discounts = ''
        return
      }
      //判断是否意见交清款项
      if(this.arrearage==0){
         this.$message.info('费用已经缴纳完毕！');
      }
    },
    //监听优惠金额
    discountsinput(val){
      if(Number(val)<0){
          this.$message.error('请输入大于0的数字');
          this.studentforms.discounts = ''
          return
      }
      if(Number(val)>=this.studentforms.course_fee){
        this.$message.error('优惠金额不能大于或者等于班型费用！');
          this.studentforms.discounts = ''
          return
      }
      if(!this.studentforms.course_fee){
        this.$message.error('请先选择班型！');
        this.studentforms.discounts = ''
        return
      }
      // if(Number(val))
    },
    //删除数据
    head_imgdel() {
      this.studentforms.head_img = ''
    },
    //选择班型 自动回填数据
    async changepackage_id(val) {
      if(!val) {
        this.isdiscounts = true
        this.studentforms.course_fee = ''
        return
      }
      //当选择班型以后恢复优惠金额输入框
      this.isdiscounts = false
      let params = {
        id: val,
      }
      let data = await readData(params)
      //回填班型费用
      this.studentforms.course_fee = data.data.data.cost
      //交费类型
      this.studentforms.pay_type = data.data.data.pay_type
    },
    //上传图片成功 返回图片URL
    head_imgok(imgUrl) {
      this.studentforms.head_img = imgUrl
    },
    closeDialog() {
      //清空支付方式价格
      for(var k in this.paytypeprice){
          this.paytypeprice[k] = ''
        }
      this.$refs['studentform'].resetFields()
      //重置表单
      this.$emit('closedialog')
    },
    //切换申领类型
    changeApplyType(e) {
 this.learntypeOptions = getSessionStorage('Optionsall')['package']
        let id = e
        if (id) {
          let newOptions = [];
          this.learntypeOptions.map((item, index) => {
            if (item.apply_type.indexOf(id) != -1) {
              newOptions.push(item)
            }
          })
          this.learntypeOptions = newOptions.concat([])
        }
        let flag=false;
        this.learntypeOptions.map((item,index)=>{
          if(item.id==this.studentforms.package_id){
              flag=true;
          }
        })
        if(!flag){
          this.studentforms.package_id=''
        }

    },

    confirmbtn() {

      //提交表单
      this.$refs['studentform'].validate(async (valid) => {
        if (!valid) return
        // TODO 提交表单
        let {
         cost_time,
         package_id,
         apply_type,
         discounts,
         enroll_cost,
         enroll_data,
         enroll_remark
        } = this.studentforms
        let params = {
          cost_time,
         package_id,
         apply_type,
         discounts,
         enroll_cost,
         enroll_data,
         enroll_remark
        }
        params.enroll_data = enroll_data.join(',')
        params.id = this.id
        //应收金额
        params.enroll_cost = this.receivableprice
        params.cost_money = this.officialprice
        params.pay_type = this.paytypeprice
        let data = await applyStudet(params)
        if(data.code=='0000'){
          //清空数据
        this.$refs['studentform'].resetFields()
        //清空支付方式价格
        for(var k in this.paytypeprice){
            this.paytypeprice[k] = ''
          }
        //编辑和成功
        this.$emit('confirm')
        }

      })
    },
  },
  mounted() {
    //选项数据
    this.schoolOptions = getSessionStorage('Optionsall')['school']
    //申领类型
    this.apply_typeOptions = getSessionStorage('Options')[1]
    //招生渠道数据
    this.channelOptions = getSessionStorage('Options')[14]
    //学习班型
    this.learntypeOptions = getSessionStorage('Optionsall')['package']
    //交费方式
    this.pay_typeOption = getSessionStorage('Options')[15]

    this.$bus.on('applyformStudent', async (val) => {
      //获取要编辑的id
      let id = val.id
      let data = await getRead({ id: id })
      let appyData = data.data
      //用户id
      this.id  = appyData.id
      //回填姓名
      this.studentforms.name = appyData.name
      //回填手机号
      this.studentforms.tel = appyData.tel
      //申领类型
      this.studentforms.apply_type = appyData.apply_type.value
      //学习班型
      this.studentforms.package_id = appyData.package_id.value
      //如果有学习班型 就 请求 接口回填班型数据
      if(appyData.package_id.value){
          //根据班型请求班型数据
          this.changepackage_id(appyData.package_id.value)
      }
    })
  },
  computed: {
    //计算应收金额 班型费用减去 优惠金额
    receivableprice() {
      return this.studentforms.course_fee - this.studentforms.discounts
    },
    //计算实收金额
    officialprice(){
      let pricearr = Object.values(this.paytypeprice);
      if(Number(this.paytypeprice.wechat) + Number(this.paytypeprice.alipay)+ Number(this.paytypeprice.money)+Number(this.paytypeprice.pos)+Number(this.paytypeprice.other)>=this.receivableprice){
        return this.receivableprice
      }else{
        return Number(this.paytypeprice.wechat) + Number(this.paytypeprice.alipay)+ Number(this.paytypeprice.money)+Number(this.paytypeprice.pos)+Number(this.paytypeprice.other)+Number(this.paytypeprice.transfer)
      }
    },
    //计算欠费
    arrearage(){
      if(this.receivableprice - this.officialprice<=0){
        return 0
      }else{
        return this.receivableprice - this.officialprice
      }

    }
  },
  destroyed() {
    this.$bus.off('applyformStudent')
  },
}
</script>

<style scoped lang='scss'>
.uploadimgarea {
  position: relative;

  .uploaditem {
    position: absolute;
    left: 0;
    top: 0;
  }
}
::v-deep {
  .paytypearea .el-input__inner {
    padding-right: 15px !important;
    width: 81px;
  }
  .el-input-group__append {
    color: #999 !important;
  }
  .el-input-group__prepend {
    background-color: #f5f7fa;
    color: #909399 !important;
    vertical-align: middle;
    display: table-cell;
    position: relative;
    // border: 1px solid #dcdfe6;
    // border-radius: 4px;
    padding: 0 9px !important ;
    width: 1px;
    white-space: nowrap;
  }
}
.moneylist {
  // margin: 5px 0 20px 0;
  display: flex;
  // margin-left: 20px;
  li {
    margin-right: 30px;
  }
}
.payTypeinput {
  padding: 0 !important;
  margin-right: 10px;
  width:40px !important;
  margin-bottom: 20px;
  &:last-child{
    margin-bottom: 0;
  }
}
</style>
